import { useRequest } from '@umijs/hooks';
import { Button, Form, Input, message, Tree, TreeSelect } from 'antd';
import { Store } from 'rc-field-form/lib/interface';
import React from 'react';
import { useSelector } from 'react-redux';
import { getSecretString } from '../../../utils/encrypt';
import { fetchRequest } from '../../../utils/Request';
import { url } from '../../../utils/url';
const { TreeNode } = Tree;
export default function ModifyUser(props: any) {



    //获取redux中的数据
    const myData = useSelector((state: any) => {

        const data = state.deptManage.deptData
        disableSelect(data)
        return {
            deptData: data,
            authData: state.staffManage.roleTable.data
        }
    })


    //递归修改item的key
    function disableSelect(arr: any[], ) {
        arr.map(item => {
            delete item.disabled
            item.key = item.deptID
            item.value = item.deptID
            if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
                return;
            } else {
                disableSelect(item.children)
            }
        })
    }

    const [form] = Form.useForm()

    const layout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    };

    const tailLayout = {
        wrapperCol: { offset: 5, span: 14 },
    };



    //渲染
    const renderTreeNodes = (data: any) =>
        data.map((item: any) => {
            //   console.log(item);
            if (item.children) {
                // console.log(item);
                // console.log(this.state.relType);
                return (
                    <TreeNode
                        title={item.title}
                        key={item.key}
                        selectable={false}
                        // dataRef={item}
                        checked={true}
                        {...item}
                    // disableCheckbox={item.ref === 3}
                    >
                        {renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return (
                <TreeNode
                    //   disableCheckbox={item.ref === 3}
                    selectable={false}
                    //   disabled={item.ref === 3}
                    checked
                    key={item.key}
                    {...item}
                />
            );
        });


    function onFinish(value: Store) {

        const data: { "roleID": string; "authID": string; }[] = []
        // console.log('roleAuth:',value.roleAuth)
        value.roleAuth.map((item: string) => {
            const temp = item.split("-");
            // console.log('temp.length:',temp.length)
            if (temp.length > 1) {
                console.log('temp:',temp)
                data.push({ "roleID": temp[0], "authID": temp[1] })
            }
        })

        const params = {
            ...value,
            phone: getSecretString(value.phone),
            roleAuth: data,
            userID: props.content.userID
        }

        // console.log(params)

        addNewUser.run(params)
    }

    async function addNewUserRequest(params: any) {
        try {
            const json = await fetchRequest(url.MODIFY_USER_URL, params);
            if (json.success) {
                message.destroy();
                message.success("修改成功!");
                props.onModifySuccess();
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message);
        }
    }

    const addNewUser = useRequest(addNewUserRequest, {
        manual: true,
        loadingDelay: 200
    })


    return (
        <Form form={form} {...layout} onFinish={onFinish} initialValues={
            {
                userName: props.content.userName,
                phone: props.content.phone,
                deptList: props.content.deptIDRelList,
                roleAuth: props.content.roleAuthMap
            }}>
            <Form.Item label="用户名" name="userName" rules={[{ required: true, message: '必须要输入用户名' }]}>
                <Input />
            </Form.Item>

            <Form.Item label="手机号" name="phone" rules={[{ required: true, message: '必须要输入手机号码' }, { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' }]}>
                <Input disabled />
            </Form.Item>

            {/* <Form.Item label="密码" name="pwd" rules={[{ required: true, message: '必须要输入密码' }, { pattern: /^.*(?=.{8,16})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*?\(\)+=\[\]\{\}_<>,.;:'"-]).*$/, message: '密码必须包含数字，字母和特殊字符,至少为8位！' }]}>
                <Input />
            </Form.Item> */}

            <Form.Item label="管理部门" name="deptList" rules={[{required: true, message: '必须要选择管理部门'}]}>
                <TreeSelect
                    treeData={myData.deptData}
                    multiple
                    maxTagCount={3}
                    showSearch={true}
                    treeNodeFilterProp={'title'}
                    allowClear
                    placeholder="请选择管理部门"
                    dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                    className="form-item"

                />
            </Form.Item>

            <Form.Item label="权限选择" name="roleAuth" valuePropName="checkedKeys">
                <Tree checkable onCheck={handleChange}>{
                    renderTreeNodes(myData.authData)}</Tree>
            </Form.Item>

            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" loading={addNewUser.loading}>提交</Button>
            </Form.Item>
        </Form>
    )


    function handleChange(data: any) {
        form.setFieldsValue({ roleAuth: data })
    }
}
